import re
from django import http
from django.contrib.auth import login, logout, authenticate
from django.http import HttpResponsePermanentRedirect
from django.urls import reverse
from django.views import View
from django.shortcuts import render, redirect
from utils import meiduo_signature
from users import contants
from celery_tasks.mail.tasks import send_user_email
from django.conf import settings
from users.forms import RegisterForm, LoginForm, ForgetForm, ModifyPwdForm
from users.models import UserProfile

# 注册
class RegisterView(View):
    def get(self, request):
        # 生成表单对象
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        """
            保存用户注册数据:
        """
        # 1.接收-------------------
        # 获取表单数据
        data = request.POST
        email = data.get('email')
        password = data.get('password')
        captcha = data.get('captcha')
        # 生成表单对象
        register_form = RegisterForm(data)
        context = {
            'msg': '该邮箱已经注册,请核查或直接登陆'
        }
        # 0.邮箱字母不区分大小写
        # 1.判断邮箱是否已经注册
        if UserProfile.objects.filter(email=email).count() > 0:
            return render(request, 'register.html', context)
        # 2.密码格式
        if not re.match('^[0-9A-Za-z]{5,20}$', password):
            return http.HttpResponseBadRequest('请输入5-20位的密码')
        # 3.验证表单
        res = register_form.is_valid()
        if res:
            # 验证成功则保存数据
            # return HttpResponse('ok')
            userprofile = UserProfile.objects.create_user(username=email, email=email, password=password)
            login(request, userprofile)
            context={
                'email': email,
                'password': password
            }
            return redirect('/')
        # 验证失败返回表单对象，在模板中渲染错误原因   register_form含有驗證碼不一致報錯信息
        return render(request, 'register.html', {'register_form': register_form})


# 登陆
class LoginView(View):
    '''登陆'''
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        data = request.POST
        username=data.get('username')
        pwd = data.get('password')
        login_form = LoginForm(data)

        if not login_form.is_valid():
            form_errors = login_form.errors
            return render(request, 'login.html', {'form_errors': form_errors})
            # return render(request, 'login.html', {'login_form': login_form})

        user = authenticate(request, username=username, password=pwd)
        if user is None:
            return render(request, 'login.html', {'msg': '用户名或密码错误'})

        login(request, user)
        return HttpResponsePermanentRedirect(reverse('index'))


# 忘记密码
class ForgetPwdView(View):
    '''忘记密码'''
    def get(self, request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    def post(self, request):
        data = request.POST
        email = data['email']
        captcha_input = data['captcha_1']
        forget_form = ForgetForm(data)
        res = forget_form.is_valid()
        # 1.表单格式验证
        if not res:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})
        try:
            user = UserProfile.objects.get(email=email)
        except:
            return http.HttpResponseBadRequest('该邮箱尚未注册,請核對郵箱，或到注冊界面注冊')
        user.email = email
        user.save()
        # 调用发邮件的任务
        token = meiduo_signature.dumps({'user_id': user.id}, contants.EMAIL_ACTIVE_EXPIRES)
        url = settings.EMAIL_ACTIVE_URL +'?token='+ token
        send_user_email.delay(email, url)
        # 响应
        return render(request, 'send_success.html')


# 重置/修改密码
class ResetView(View):
    def get(self, request):

        token = request.GET.get('token')
        # 验证
        if not all([token]):
            return http.HttpResponseBadRequest('参数不完整')
        json = meiduo_signature.loads(token, contants.EMAIL_ACTIVE_EXPIRES)

        if json is None:
            return render(request, 'active_fail.html')
        user_id = json.get('user_id')
        # 处理
        try:
            user = UserProfile.objects.get(pk=user_id)
        except:
            return render(request, 'active_fail.html')

        # 响应
        login(request,user)
        return render(request, 'password_reset.html', {'email': user.email})

    def post(self, request):
        data = request.POST
        modify_form = ModifyPwdForm(data)
        user = request.user
        password1 = data['password1']
        password2 = data['password2']
        res = modify_form.is_valid()
        error = modify_form.errors
        if res:
            if password1 == password2:
                user.set_password(password1)
                user.save()
                return http.HttpResponse('修改密碼成功')
            else:
                # return http.HttpResponse('修改密碼失敗')
                return render(request, 'password_reset.html', {'msg': '兩次輸入的密碼不一致'})
        else:
            # return render(request, 'password_reset.html', {'msg': '兩次輸入的密碼不一致'})
            return render(request, 'password_reset.html', {'modify_form': modify_form})


# 退出登陆
class LogoutView(View):
    def get(self, request):
        # 登出
        logout(request)
        return render(request, 'login.html')



